package fr.ifisher.dao.implementation;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Criteria;
import org.hibernate.Session;

import fr.ifisher.dao.inter.IGenericDao;

public class GenericDao<T, PK extends Serializable> implements
		IGenericDao<T, PK> {

	public final static String LIKE_SEARCH_CHAR = "%";

	private Class<T> entityClass;

	@PersistenceContext
	protected EntityManager em;

	@SuppressWarnings("unchecked")
	public GenericDao() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass()
				.getGenericSuperclass();
		this.entityClass = (Class<T>) genericSuperclass
				.getActualTypeArguments()[0];
	}

	public GenericDao(final Class<T> entityClass) {
		super();
		this.entityClass = entityClass;
	}

	@Override
	public T create(T object) {
		em.persist(object);
		// em.flush();
		return object;
	}

	@Override
	public T read(PK id) {
		return em.find(entityClass, id);
	}

	@Override
	public T update(T object) {
		return em.merge(object);
	}

	@Override
	public void delete(T object) {
		object = em.merge(object);
		em.remove(object);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> getAll() {
		Session session = (Session) em.getDelegate();
		Criteria crit = session.createCriteria(entityClass);
		return crit.list();
	}

}
